$(document).ready(function(){
	// Show #newTournamentDiv
	$("#createTournamentBtn").click(function(){
		$("#createTournamentDiv").slideToggle();
	});
	
	$("#submitMatch").click(function(){
		var datastring = "d=" + $("#date").val() + "&p1=" + $("#player1").val() + "&p2=" + $("#player2").val() +
			"&p3=" + $("#player3").val() + "&p4=" + $("#player4").val() + "&s1=" + $("#score1").val() +
			"&s2=" + $("#score2").val() + "&loc=" + $("#location").val() + "&n=" + $("#notes").val()
		
		$.ajax({
			url: "/addMatch",
			type: "GET",
			data: datastring,
			success: function(data,status,resp) {
				if (resp.getResponseHeader("added") == "1") {
					$("#foosFirstRow").after("<tr>" +
						"<td>" + $("#date").val() + "</td><td>" + $("#player1").val() + "</td><td>" + $("#player2").val() + "</td><td>" +
						$("#player3").val() + "</td><td>" + $("#player4").val() + "</td><td>" + $("#score1").val() + 
						"</td><td>" + $("#score2").val() + "</td><td>" + $("#location").val() + "</td><td>" + 
						$("#notes").val() + "</tr>");
				}
			}
		})
	});
	
	/* Competition old version below */
	
	// Sign up for a match
	function signUpForMatch(){
		var datastring = "matchKey=" + $("input#key").val();
		
		if ($("#newPlayer").value != "")
			datastring+= "&newPlayer=" + $("#newPlayer").val();
		
		$.ajax({
			url: "/signUp",
			type: "POST",
			data: datastring,
			success: function(data,status,resp) {
				if (resp.getResponseHeader("added") == "1") {
					username = resp.getResponseHeader("username");
					//userID = resp.getResponseHeader("userID");
					$(".playerListDiv").append('<div id="'+ username +'PlrDiv">'+username+'</div>');
					
					//Disable signUp button and enable signOut one
					$("#signUp").attr("disabled", "disabled");
					$("#signOut").removeAttr("disabled");
				}
			}
		}
		);
	}
	
	$("#signUp").click(signUpForMatch);
	
	//Sign out from a match
	$("#signOut").click(function(event){
		var datastring = "matchKey=" + $("input#key").val();
		
		$.ajax({
			url: "/signOut",
			type: "POST",
			data: datastring,
			success: function(data,status,resp) {
				if (resp.getResponseHeader("removed") == "1") {
					//$("#" + resp.getResponseHeader("userID") + "PlrDiv").remove();
					$("#" + resp.getResponseHeader("username") + "PlrDiv").remove();
					
					//Enable signUp button and disable signOut one
					$("#signUp").removeAttr("disabled");
					$("#signOut").attr("disabled", "disabled");
				}
			}
		}
		);
	});
	
	//Manually add a player to the match
	//signUpForMatch will get the name of the player from the popup
	$("#addPlayer").click(function(){
		$(".addPlayerDiv").slideToggle();
	});
	
	//If the Submit player button is clicked, finalize the sign up
	$("#newPlayerBtn").click(signUpForMatch);
	
});